import { create, remove, update, query, changeStatus } from '../services/transferFiles';
//import qs from 'qs';
import { parse } from 'qs';

export default {

  namespace: 'transferFiles',

  state: {
    list: [],
    loading: false,
    total: null,
    current: 1,
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/transferFiles') {
          dispatch({
            type: 'query',
            payload: location.query,
          });
        }
      });
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      yield put({ type: 'showLoading' });
      const { data } = yield call(query, parse(payload));
      if (undefined === data.err) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.result.data,
            total: data.result.data.length,
            current: payload.page,
          },
        });
      } else {
        yield put({
          type: 'querySuccess',
          payload: {
            list: [],
            total: 0,
            current: 1,
          },
        });
      }
    },
    *'delete'({ payload }, { call, put }) {
      yield put({ type: 'showLoading' });
      const { data } = yield call(remove, { id: payload });
      if (data && data.success) {
        yield put({
          type: 'deleteSuccess',
          payload,
        });
      }
    },
    *'clear'({ payload }, { call, put }) {
      yield put({
        type: 'clearPage',
      });
    },
  },

  reducers: {
    showLoading(state) {
      return { ...state, loading: true };
    },
    deleteSuccess(state, action) {
      const id = action.payload;
      const newList = state.list.filter(user => user.id !== id);
      return { ...state, list: newList, loading: false };
    },
    querySuccess(state, action) {
      return { ...state, ...action.payload, loading: false };
    },
    showModal(state, action) {
      return { ...state, ...action.payload, modalVisible: true };
    },
    hideModal(state) {
      return { ...state, modalVisible: false };
    },
    clearPage(state) {
      return { ...state, list:[], total:0, loading: false  };
    },
  },

};
